<template>
  <div class="department-management">
    <!-- 页面头部 -->
    <div class="flex justify-between items-center mb-6">
      <h1 class="text-2xl font-bold text-gray-800">部门管理</h1>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增部门
      </el-button>
    </div>

    <!-- 统计卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
      <el-card class="stat-card">
        <div class="flex items-center">
          <div class="stat-icon bg-blue-100 text-blue-600">
            <el-icon size="24"><OfficeBuilding /></el-icon>
          </div>
          <div class="ml-4">
            <div class="text-2xl font-bold text-gray-800">{{ stats.totalDepartments }}</div>
            <div class="text-sm text-gray-500">总部门数</div>
          </div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="flex items-center">
          <div class="stat-icon bg-green-100 text-green-600">
            <el-icon size="24"><User /></el-icon>
          </div>
          <div class="ml-4">
            <div class="text-2xl font-bold text-gray-800">{{ stats.totalEmployees }}</div>
            <div class="text-sm text-gray-500">总员工数</div>
          </div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="flex items-center">
          <div class="stat-icon bg-yellow-100 text-yellow-600">
            <el-icon size="24"><TrendCharts /></el-icon>
          </div>
          <div class="ml-4">
            <div class="text-2xl font-bold text-gray-800">{{ stats.maxDepth }}</div>
            <div class="text-sm text-gray-500">最大层级</div>
          </div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="flex items-center">
          <div class="stat-icon bg-purple-100 text-purple-600">
            <el-icon size="24"><UserFilled /></el-icon>
          </div>
          <div class="ml-4">
            <div class="text-2xl font-bold text-gray-800">{{ stats.avgEmployeesPerDept }}</div>
            <div class="text-sm text-gray-500">平均人数</div>
          </div>
        </div>
      </el-card>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
      <!-- 部门树 -->
      <div class="lg:col-span-1">
        <el-card>
          <template #header>
            <div class="flex justify-between items-center">
              <h3 class="text-lg font-semibold">部门结构</h3>
              <div class="flex gap-2">
                <el-button size="small" @click="expandAll">
                  <el-icon><Expand /></el-icon>
                  展开全部
                </el-button>
                <el-button size="small" @click="collapseAll">
                  <el-icon><Fold /></el-icon>
                  收起全部
                </el-button>
              </div>
            </div>
          </template>
          
          <el-tree
            ref="treeRef"
            :data="departmentTree"
            :props="treeProps"
            node-key="id"
            :default-expand-all="false"
            :expand-on-click-node="false"
            highlight-current
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <div class="flex items-center justify-between w-full">
                <div class="flex items-center">
                  <el-icon class="mr-2 text-blue-600">
                    <OfficeBuilding v-if="data.level === 1" />
                    <Collection v-else />
                  </el-icon>
                  <span class="font-medium">{{ data.name }}</span>
                  <el-tag size="small" class="ml-2" type="info">
                    {{ data.employeeCount }}人
                  </el-tag>
                </div>
                <div class="flex gap-1">
                  <el-button
                    size="small"
                    type="primary"
                    @click.stop="handleAddChild(data)"
                    link
                  >
                    <el-icon><Plus /></el-icon>
                  </el-button>
                  <el-button
                    size="small"
                    type="warning"
                    @click.stop="handleEdit(data)"
                    link
                  >
                    <el-icon><Edit /></el-icon>
                  </el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click.stop="handleDelete(data)"
                    link
                    v-if="data.employeeCount === 0"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
            </template>
          </el-tree>
        </el-card>
      </div>

      <!-- 部门详情和员工列表 -->
      <div class="lg:col-span-2">
        <el-card v-if="selectedDepartment">
          <template #header>
            <div class="flex justify-between items-center">
              <h3 class="text-lg font-semibold">{{ selectedDepartment.name }} - 详细信息</h3>
              <el-button type="primary" @click="handleEdit(selectedDepartment)">
                <el-icon><Edit /></el-icon>
                编辑部门
              </el-button>
            </div>
          </template>
          
          <!-- 部门信息 -->
          <div class="mb-6">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="部门名称">{{ selectedDepartment.name }}</el-descriptions-item>
              <el-descriptions-item label="部门编码">{{ selectedDepartment.code }}</el-descriptions-item>
              <el-descriptions-item label="部门负责人">{{ selectedDepartment.manager || '暂无' }}</el-descriptions-item>
              <el-descriptions-item label="员工人数">{{ selectedDepartment.employeeCount }}人</el-descriptions-item>
              <el-descriptions-item label="创建时间">{{ selectedDepartment.createTime }}</el-descriptions-item>
              <el-descriptions-item label="状态">
                <el-tag :type="selectedDepartment.status === '启用' ? 'success' : 'danger'">
                  {{ selectedDepartment.status }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="部门描述" :span="2">
                {{ selectedDepartment.description || '暂无描述' }}
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 员工列表 -->
          <div>
            <div class="flex justify-between items-center mb-4">
              <h4 class="text-lg font-semibold">部门员工</h4>
              <el-input
                v-model="employeeSearch"
                placeholder="搜索员工"
                style="width: 200px"
                clearable
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
            
            <el-table
              :data="filteredEmployees"
              style="width: 100%"
              v-loading="employeeLoading"
              stripe
            >
              <el-table-column prop="name" label="姓名" width="100" />
              <el-table-column prop="employeeNo" label="工号" width="120" />
              <el-table-column prop="position" label="职位" width="120" />
              <el-table-column prop="phone" label="手机号" width="130" />
              <el-table-column prop="email" label="邮箱" min-width="150" />
              <el-table-column prop="hireDate" label="入职日期" width="120" />
              <el-table-column prop="status" label="状态" width="80">
                <template #default="{ row }">
                  <el-tag
                    :type="getEmployeeStatusType(row.status)"
                    size="small"
                  >
                    {{ row.status }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120">
                <template #default="{ row }">
                  <el-button
                    type="primary"
                    size="small"
                    @click="viewEmployee(row)"
                    link
                  >
                    <el-icon><View /></el-icon>
                    查看
                  </el-button>
                  <el-button
                    type="warning"
                    size="small"
                    @click="handleTransferEmployee(row)"
                    link
                  >
                    <el-icon><Switch /></el-icon>
                    调动
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
        
        <!-- 空状态 -->
        <el-card v-else>
          <el-empty description="请选择一个部门查看详情" />
        </el-card>
      </div>
    </div>

    <!-- 新增/编辑部门对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑部门' : '新增部门'"
      width="500px"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="上级部门" v-if="!isEdit">
          <el-tree-select
            v-model="form.parentId"
            :data="departmentTree"
            :props="treeProps"
            placeholder="请选择上级部门"
            style="width: 100%"
            clearable
            check-strictly
          />
        </el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入部门编码" />
        </el-form-item>
        <el-form-item label="部门负责人">
          <el-select
            v-model="form.managerId"
            placeholder="请选择部门负责人"
            style="width: 100%"
            clearable
            filterable
          >
            <el-option
              v-for="employee in allEmployees"
              :key="employee.id"
              :label="employee.name"
              :value="employee.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门状态">
          <el-radio-group v-model="form.status">
            <el-radio label="启用">启用</el-radio>
            <el-radio label="禁用">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="部门描述">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入部门描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 员工调动对话框 -->
    <el-dialog
      v-model="transferDialogVisible"
      title="员工调动"
      width="400px"
    >
      <el-form :model="transferForm" label-width="100px">
        <el-form-item label="员工姓名">
          <el-input v-model="transferEmployee.name" disabled />
        </el-form-item>
        <el-form-item label="当前部门">
          <el-input v-model="transferEmployee.department" disabled />
        </el-form-item>
        <el-form-item label="调动到">
          <el-tree-select
            v-model="transferForm.targetDepartmentId"
            :data="departmentTree"
            :props="treeProps"
            placeholder="请选择目标部门"
            style="width: 100%"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="调动原因">
          <el-input
            v-model="transferForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入调动原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="transferDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleTransferSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  OfficeBuilding,
  User,
  TrendCharts,
  UserFilled,
  Expand,
  Fold,
  Collection,
  Edit,
  Delete,
  Search,
  View,
  Switch
} from '@element-plus/icons-vue'

// 响应式数据
const treeRef = ref()
const formRef = ref()
const dialogVisible = ref(false)
const transferDialogVisible = ref(false)
const isEdit = ref(false)
const employeeLoading = ref(false)
const employeeSearch = ref('')
const selectedDepartment = ref(null)
const transferEmployee = ref({})

// 统计数据
const stats = reactive({
  totalDepartments: 12,
  totalEmployees: 156,
  maxDepth: 3,
  avgEmployeesPerDept: 13
})

// 树形组件配置
const treeProps = {
  children: 'children',
  label: 'name',
  value: 'id'
}

// 表单数据
const form = reactive({
  id: null,
  parentId: null,
  name: '',
  code: '',
  managerId: null,
  status: '启用',
  description: ''
})

// 调动表单
const transferForm = reactive({
  targetDepartmentId: null,
  reason: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    { min: 2, max: 20, message: '部门名称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入部门编码', trigger: 'blur' },
    { pattern: /^[A-Z0-9]{2,10}$/, message: '部门编码只能包含大写字母和数字，长度2-10位', trigger: 'blur' }
  ]
}

// 部门树数据
const departmentTree = ref([])

// 部门员工列表
const departmentEmployees = ref([])

// 所有员工列表（用于选择负责人）
const allEmployees = ref([])

// 过滤后的员工列表
const filteredEmployees = computed(() => {
  if (!employeeSearch.value) {
    return departmentEmployees.value
  }
  return departmentEmployees.value.filter(employee => 
    employee.name.includes(employeeSearch.value) ||
    employee.employeeNo.includes(employeeSearch.value) ||
    employee.position.includes(employeeSearch.value)
  )
})

// 获取员工状态类型
const getEmployeeStatusType = (status) => {
  const statusMap = {
    '在职': 'success',
    '离职': 'danger',
    '休假': 'warning'
  }
  return statusMap[status] || 'info'
}

// 获取部门树数据
const getDepartmentTree = async () => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 模拟数据
    const mockData = [
      {
        id: 1,
        name: '总公司',
        code: 'HQ',
        level: 1,
        parentId: null,
        manager: '张总',
        managerId: 1,
        employeeCount: 156,
        status: '启用',
        description: '公司总部',
        createTime: '2023-01-01',
        children: [
          {
            id: 2,
            name: '技术部',
            code: 'TECH',
            level: 2,
            parentId: 1,
            manager: '李经理',
            managerId: 2,
            employeeCount: 45,
            status: '启用',
            description: '负责技术研发',
            createTime: '2023-01-15',
            children: [
              {
                id: 3,
                name: '前端组',
                code: 'FE',
                level: 3,
                parentId: 2,
                manager: '王组长',
                managerId: 3,
                employeeCount: 15,
                status: '启用',
                description: '前端开发团队',
                createTime: '2023-02-01'
              },
              {
                id: 4,
                name: '后端组',
                code: 'BE',
                level: 3,
                parentId: 2,
                manager: '赵组长',
                managerId: 4,
                employeeCount: 20,
                status: '启用',
                description: '后端开发团队',
                createTime: '2023-02-01'
              },
              {
                id: 5,
                name: '测试组',
                code: 'QA',
                level: 3,
                parentId: 2,
                manager: '孙组长',
                managerId: 5,
                employeeCount: 10,
                status: '启用',
                description: '质量保证团队',
                createTime: '2023-02-15'
              }
            ]
          },
          {
            id: 6,
            name: '销售部',
            code: 'SALES',
            level: 2,
            parentId: 1,
            manager: '刘经理',
            managerId: 6,
            employeeCount: 32,
            status: '启用',
            description: '负责销售业务',
            createTime: '2023-01-20',
            children: [
              {
                id: 7,
                name: '华北区',
                code: 'NORTH',
                level: 3,
                parentId: 6,
                manager: '周主管',
                managerId: 7,
                employeeCount: 12,
                status: '启用',
                description: '华北地区销售',
                createTime: '2023-03-01'
              },
              {
                id: 8,
                name: '华南区',
                code: 'SOUTH',
                level: 3,
                parentId: 6,
                manager: '吴主管',
                managerId: 8,
                employeeCount: 20,
                status: '启用',
                description: '华南地区销售',
                createTime: '2023-03-01'
              }
            ]
          },
          {
            id: 9,
            name: '人事部',
            code: 'HR',
            level: 2,
            parentId: 1,
            manager: '陈经理',
            managerId: 9,
            employeeCount: 8,
            status: '启用',
            description: '人力资源管理',
            createTime: '2023-01-10'
          },
          {
            id: 10,
            name: '财务部',
            code: 'FIN',
            level: 2,
            parentId: 1,
            manager: '郑经理',
            managerId: 10,
            employeeCount: 12,
            status: '启用',
            description: '财务管理',
            createTime: '2023-01-12'
          },
          {
            id: 11,
            name: '市场部',
            code: 'MKT',
            level: 2,
            parentId: 1,
            manager: '何经理',
            managerId: 11,
            employeeCount: 15,
            status: '启用',
            description: '市场推广',
            createTime: '2023-01-25'
          },
          {
            id: 12,
            name: '行政部',
            code: 'ADMIN',
            level: 2,
            parentId: 1,
            manager: '许经理',
            managerId: 12,
            employeeCount: 6,
            status: '启用',
            description: '行政管理',
            createTime: '2023-01-30'
          }
        ]
      }
    ]
    
    departmentTree.value = mockData
  } catch (error) {
    ElMessage.error('获取部门数据失败')
  }
}

// 获取所有员工
const getAllEmployees = async () => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 300))
    
    // 模拟数据
    const mockData = [
      { id: 1, name: '张总', employeeNo: 'CEO001' },
      { id: 2, name: '李经理', employeeNo: 'MGR001' },
      { id: 3, name: '王组长', employeeNo: 'TL001' },
      { id: 4, name: '赵组长', employeeNo: 'TL002' },
      { id: 5, name: '孙组长', employeeNo: 'TL003' },
      { id: 6, name: '刘经理', employeeNo: 'MGR002' },
      { id: 7, name: '周主管', employeeNo: 'SUP001' },
      { id: 8, name: '吴主管', employeeNo: 'SUP002' },
      { id: 9, name: '陈经理', employeeNo: 'MGR003' },
      { id: 10, name: '郑经理', employeeNo: 'MGR004' },
      { id: 11, name: '何经理', employeeNo: 'MGR005' },
      { id: 12, name: '许经理', employeeNo: 'MGR006' }
    ]
    
    allEmployees.value = mockData
  } catch (error) {
    ElMessage.error('获取员工数据失败')
  }
}

// 获取部门员工
const getDepartmentEmployees = async (departmentId) => {
  employeeLoading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 模拟数据
    const mockData = [
      {
        id: 1,
        name: '张三',
        employeeNo: 'EMP001',
        position: '高级工程师',
        phone: '13800138001',
        email: 'zhangsan@company.com',
        hireDate: '2023-03-15',
        status: '在职',
        departmentId: departmentId
      },
      {
        id: 2,
        name: '李四',
        employeeNo: 'EMP002',
        position: '工程师',
        phone: '13800138002',
        email: 'lisi@company.com',
        hireDate: '2023-04-20',
        status: '在职',
        departmentId: departmentId
      },
      {
        id: 3,
        name: '王五',
        employeeNo: 'EMP003',
        position: '初级工程师',
        phone: '13800138003',
        email: 'wangwu@company.com',
        hireDate: '2023-06-10',
        status: '在职',
        departmentId: departmentId
      }
    ]
    
    departmentEmployees.value = mockData
  } catch (error) {
    ElMessage.error('获取部门员工失败')
  } finally {
    employeeLoading.value = false
  }
}

// 展开全部
const expandAll = () => {
  const allNodes = treeRef.value.store.nodesMap
  for (let nodeId in allNodes) {
    allNodes[nodeId].expanded = true
  }
}

// 收起全部
const collapseAll = () => {
  const allNodes = treeRef.value.store.nodesMap
  for (let nodeId in allNodes) {
    allNodes[nodeId].expanded = false
  }
}

// 节点点击
const handleNodeClick = (data) => {
  selectedDepartment.value = data
  getDepartmentEmployees(data.id)
}

// 新增部门
const handleAdd = () => {
  isEdit.value = false
  Object.assign(form, {
    id: null,
    parentId: null,
    name: '',
    code: '',
    managerId: null,
    status: '启用',
    description: ''
  })
  dialogVisible.value = true
}

// 新增子部门
const handleAddChild = (data) => {
  isEdit.value = false
  Object.assign(form, {
    id: null,
    parentId: data.id,
    name: '',
    code: '',
    managerId: null,
    status: '启用',
    description: ''
  })
  dialogVisible.value = true
}

// 编辑部门
const handleEdit = (data) => {
  isEdit.value = true
  Object.assign(form, {
    id: data.id,
    parentId: data.parentId,
    name: data.name,
    code: data.code,
    managerId: data.managerId,
    status: data.status,
    description: data.description
  })
  dialogVisible.value = true
}

// 删除部门
const handleDelete = async (data) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除部门 "${data.name}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success('部门删除成功')
    getDepartmentTree()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('部门删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success(isEdit.value ? '部门更新成功' : '部门创建成功')
    dialogVisible.value = false
    getDepartmentTree()
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 查看员工
const viewEmployee = (employee) => {
  ElMessage.info(`查看员工：${employee.name}`)
}

// 调动员工
const handleTransferEmployee = (employee) => {
  transferEmployee.value = {
    ...employee,
    department: selectedDepartment.value.name
  }
  Object.assign(transferForm, {
    targetDepartmentId: null,
    reason: ''
  })
  transferDialogVisible.value = true
}

// 提交调动
const handleTransferSubmit = async () => {
  if (!transferForm.targetDepartmentId) {
    ElMessage.warning('请选择目标部门')
    return
  }
  
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success('员工调动成功')
    transferDialogVisible.value = false
    getDepartmentEmployees(selectedDepartment.value.id)
  } catch (error) {
    ElMessage.error('员工调动失败')
  }
}

// 组件挂载时获取数据
onMounted(() => {
  getDepartmentTree()
  getAllEmployees()
})
</script>

<style scoped>
.department-management {
  padding: 20px;
}

.stat-card {
  cursor: pointer;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-tree-node__content) {
  height: 40px;
}

:deep(.el-tree-node__expand-icon) {
  color: #409eff;
}
</style>